<?
$slug = $_SERVER['REQUEST_URI'];
if(strpos($slug,"#") !== false) {
	$cache_name = md5(substr($slug,0,strpos($slug,"#"))) . ".cache";
} else {
	$cache_name = md5($slug) . ".cache";
}
$cache_loc = root_dir . "drizzo/cache/$cache_name";

function drizzo_cache_page() {
	global $slug, $cache_name, $cache_loc;
	if(drizzo_global_options('use_cache') == 1) {
		if((file_exists($cache_loc) && (time() - filectime($cache_loc)) > (drizzo_global_options('cache_time') * 60)) || !file_exists($cache_loc)) {
			$page = ob_get_contents();
			$page = str_replace('</html>',"<!--cache: " . gmdate(drizzo_global_options('time_format'), time() + ((drizzo_global_options('timezone_offset') + date('I')) * 60 * 60)) . "-->\n</html>",$page);
			if($file = fopen($cache_loc,"w")) {
				fwrite($file,$page);
				fclose($file);
			}
		}
	}
}

function drizzo_cache() {
	global $slug, $cache_name, $cache_loc;
	if(drizzo_global_options('use_cache') == 1) {
		if((drizzo_global_options('cache_type') == 'always' || (drizzo_global_options('cache_type') == 'progressive' && drizzo_server_load() == true)) && file_exists($cache_loc) && (time() - filectime($cache_loc)) < (drizzo_global_options('cache_time') * 60)) {
			include($cache_loc);
			die();
		}
	}
}

function drizzo_cache_destroy($permalink) {
	$cache_name = md5($permalink);
	$cache_loc = root_dir . "drizzo/cache/$cache_name";
	if(file_exists($cache_loc)) {
		unlink($cache_loc);
	}
}

function drizzo_cache_empty() {
	$cache_loc = root_dir . "drizzo/cache/";
	if(is_writable($cache_loc)) {
		if($directory = opendir($cache_loc)) {
			while(false !== ($file = readdir($directory))) {
				if($file != '.' && $file != '..' && substr($file,-6) == '.cache') {
					@unlink($cache_loc . $file);
				}
			}
			closedir($directory);
		}
	}
}

function drizzo_server_load() { // Taken from http://mpwebwizard.com/free_stuff/server_load_monitor under a GNU GPL Version 2 License
	$load = @exec('uptime'); 
	preg_match ("/averages?: ([0-9\.]+),[\s]+([0-9\.]+),[\s]+([0-9\.]+)/", $load, $avgs);
	if($avgs[0] > drizzo_global_options('cache_server_load')) {
		return true;
	} elseif(drizzo_db_connect() == false) {
		return true;
	} else {
		return false;
	}
}
?>